import pygame
import random
import time

# 初始化 Pygame
pygame.init()

# 游戏窗口配置
WIDTH, HEIGHT = 800, 600
BLOCK_SIZE = 20
SPEED = 10  # 初始速度

# 颜色定义
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 创建窗口
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Pygame 贪吃蛇")

# 时钟控制帧率
clock = pygame.time.Clock()

# 字体设置
font = pygame.font.SysFont("arial", 36)

class Snake:
    def __init__(self):
        self.body = [(WIDTH//2, HEIGHT//2)]  # 初始位置
        self.direction = "RIGHT"  # 初始方向
        self.grow = False  # 是否增长

    def move(self):
        # 计算新头部位置
        head_x, head_y = self.body[0]
        if self.direction == "UP":    head_y -= BLOCK_SIZE
        elif self.direction == "DOWN": head_y += BLOCK_SIZE
        elif self.direction == "LEFT": head_x -= BLOCK_SIZE
        elif self.direction == "RIGHT": head_x += BLOCK_SIZE

        # 插入新头部并移除尾部（除非需要增长）
        self.body.insert(0, (head_x, head_y))
        if not self.grow:
            self.body.pop()
        else:
            self.grow = False

    def change_direction(self, new_dir):
        # 防止反向移动
        if (new_dir == "UP" and self.direction != "DOWN") or \
           (new_dir == "DOWN" and self.direction != "UP") or \
           (new_dir == "LEFT" and self.direction != "RIGHT") or \
           (new_dir == "RIGHT" and self.direction != "LEFT"):
            self.direction = new_dir

def generate_food(snake):
    while True:
        food_x = random.randint(0, (WIDTH-BLOCK_SIZE)//BLOCK_SIZE) * BLOCK_SIZE
        food_y = random.randint(0, (HEIGHT-BLOCK_SIZE)//BLOCK_SIZE) * BLOCK_SIZE
        if (food_x, food_y) not in snake.body:
            return (food_x, food_y)

def draw_elements(snake, food, score):
    # 清屏
    screen.fill(BLACK)

    # 绘制蛇
    for segment in snake.body:
        pygame.draw.rect(screen, GREEN, pygame.Rect(segment[0], segment[1], BLOCK_SIZE, BLOCK_SIZE))

    # 绘制食物
    pygame.draw.rect(screen, RED, pygame.Rect(food[0], food[1], BLOCK_SIZE, BLOCK_SIZE))

    # 显示分数
    score_text = font.render(f"Score: {score}", True, WHITE)
    screen.blit(score_text, (10, 10))

def game_over(screen, score):
    # 游戏结束界面
    screen.fill(BLACK)
    game_over_text = font.render("GAME OVER!", True, WHITE)
    score_text = font.render(f"Final Score: {score}", True, WHITE)
    screen.blit(game_over_text, (WIDTH//2 - 150, HEIGHT//2 - 50))
    screen.blit(score_text, (WIDTH//2 - 120, HEIGHT//2 + 20))
    pygame.display.update()
    time.sleep(3)
def show_start_screen():
    """显示开始界面，等待任意按键"""
    screen.fill(BLACK)
    start_text = font.render("Press Any Key to Start", True, WHITE)
    screen.blit(start_text, (WIDTH//2 - 180, HEIGHT//2))
    pygame.display.update()
    
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:  # 检测任意按键
                waiting = False
def main():
    global SPEED
    snake = Snake()
    food = generate_food(snake)
    score = 0
    running = True
    
    # 添加开始界面
    show_start_screen()  # 等待按键

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:    snake.change_direction("UP")
                elif event.key == pygame.K_DOWN: snake.change_direction("DOWN")
                elif event.key == pygame.K_LEFT: snake.change_direction("LEFT")
                elif event.key == pygame.K_RIGHT: snake.change_direction("RIGHT")

        # 移动蛇
        snake.move()

        # 碰撞检测
        head = snake.body[0]
        if (head[0] < 0 or head[0] >= WIDTH or
            head[1] < 0 or head[1] >= HEIGHT or
            head in snake.body[1:]):
            game_over(screen, score)
            return

        # 吃到食物
        if head == food:
            score += 10
            snake.grow = True
            food = generate_food(snake)
            SPEED += 2  # 速度提升

        # 绘制元素
        draw_elements(snake, food, score)
        pygame.display.update()
        clock.tick(SPEED)

if __name__ == "__main__":
    main()